"""
调用bapi接口
"""
import requests
import os
import sys
from pathlib import Path
from os.path import dirname
path = dirname(str(Path(__file__).resolve().parents[2]))
if path not in sys.path:
    sys.path.append(path)

class BapiCaller():

    headers_xopyx = {
                "accept":"*/*",
                "accept-encoding":"gzip, deflate, br, zstd",
                "accept-language":"zh-CN,zh;q=0.9",
                "connection":"keep-alive",
                "content-type":"application/x-www-form-urlencoded",
                "cookie":"UT1=ut-4-IVxHIH2kokU-hA; xkw-device-id=E75F6C2A25254E577D49498F723C0AD8",
                "doc-x-bapi-app-id":"rbm",
                "doc-x-secret":"E#tYMQcmSLpWW*Jbo)oGeS4~SZ6&26LW",
                "doc-x-xop-app-id":"rbm",
                "host":"test-gw.xkw.com",
                "referer":"",
                "request-origion":"Knife4j",
                "sec-ch-ua":"Google Chrome;v=131, Chromium;v=131, Not_A Brand;v=24",
                "sec-ch-ua-mobile":"?0",
                "sec-ch-ua-platform":"macOS",
                "sec-fetch-dest":"empty",
                "sec-fetch-mode":"cors",
                "sec-fetch-site":"same-origin",
                "user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "x-doc-service-path":"/xopyx"
    }

    def __init__(self, prodEnv: bool, app_id: str, app_secret: str) -> None:
        self._app_id = app_id
        self._app_secret = app_secret
        if (not prodEnv):
            self.domain = "https://test-gw.xkw.com/"
        else:
            self.domain = "https://gw.xkw.com/"
        self.headers_xopyx["host"] = self.domain.split("//")[1].split("/")[0]
        self.headers_xopyx["referer"] = f"{self.domain}/help/doc.html"
        self.headers_xopyx["doc-x-bapi-app-id"] = self._app_id
        self.headers_xopyx["doc-x-secret"] = self._app_secret
        self.headers_xopyx["doc-x-xop-app-id"] = self._app_id
        # with open("xkw/bapi/cookie.txt", "r") as fin:
        #     self.headers_xopyx["cookie"] = fin.read()

    def get(self, uri):
        url = f"{self.domain}help/api/{self._app_id}/{uri}"
        response = requests.get(url,headers=self.headers_xopyx)
        response.encoding = "utf-8"
        if response.status_code != 200:
            print(f"调用bapi接口{uri}失败: {response.json()}")
            return None
        return response.json()
    
    def post(self, uri, data):
        url = f"{self.domain}help/api/{self._app_id}/{uri}"
        response = requests.get(url,headers=self.headers_xopyx)
        if response.status_code != 200:
            print(f"调用bapi接口{uri}失败: {response.json()}")
            return None
        return response.json()


